package com.waypolice.manager.controller;


import com.baidu.unbiz.fluentvalidator.ComplexResult;
import com.baidu.unbiz.fluentvalidator.FluentValidator;
import com.baidu.unbiz.fluentvalidator.ResultCollectors;
import com.waypolice.base.BaseController;
import com.waypolice.common.pojo.UpmsResult;
import com.waypolice.common.pojo.UpmsResultConstant;
import com.waypolice.common.utils.DateTimeUtil;
import com.waypolice.common.utils.StringUtil;
import com.waypolice.common.validator.LengthValidator;
import com.waypolice.pojo.*;
import com.waypolice.manager.service.UpmsArchivesTypesService;
import com.waypolice.manager.service.UpmsFileNumService;
import com.waypolice.manager.service.UpmsFondsManageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 全宗管理controller
 * @author  lzh on 2018/3/14.
 */
@Controller
@Api(value = "全宗管理", description = "全宗管理")
@RequestMapping("/manage/fonds")
public class UpmsFondsController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UpmsFondsController.class);

    @Autowired
    private UpmsFondsManageService upmsFondsManageService;

    @Autowired
    private UpmsArchivesTypesService upmsArchivesTypesService;

    @Autowired
    private UpmsFileNumService upmsFileNumService;

    @ApiOperation(value = "全宗首页")
    @RequiresPermissions("upms:fonds:read")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return "/manage/fonds/index";
    }

    @ApiOperation(value = "全宗列表")
    @RequiresPermissions("upms:fonds:read")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Object list(
            @RequestParam(required = false, defaultValue = "0", value = "offset") int offset,
            @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
            @RequestParam(required = false, value = "sort") String sort,
            @RequestParam(required = false, value = "order") String order,
            @RequestParam(required = false, defaultValue = "", value = "search") String search) {
        UpmsFondsManageExample upmsFondsManageExample = new UpmsFondsManageExample();
        UpmsFondsManageExample.Criteria criteria = upmsFondsManageExample.createCriteria();
        if (StringUtils.isBlank(sort)){
            sort = "fondsId";
        }
        if (!StringUtils.isBlank(sort) && !StringUtils.isBlank(order)) {
            sort = StringUtil.frontStrongToOracleString(sort);
            upmsFondsManageExample.setOrderByClause(sort + " " + order);
        }
        if (StringUtils.isNotBlank(search)) {
            criteria.andFondsNameLike("%" + search + "%");
        }
       criteria.andStr1EqualTo("0");
        List<UpmsFondsManage> rows = upmsFondsManageService.selectByExampleForOffsetPage(upmsFondsManageExample,offset,limit);
        long total = upmsFondsManageService.countByExample(upmsFondsManageExample);
        Map<String, Object> result = new HashMap<>();
        result.put("rows", rows);
        result.put("total", total);
        return result;
    }
    @ApiOperation(value = "全宗列表")
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public List<UpmsFondsManage> list(){
        UpmsFondsManageExample example = new UpmsFondsManageExample();
        example.createCriteria().andStr1EqualTo("0");
        example.setOrderByClause("FONDS_NUM ASC");
        List<UpmsFondsManage> upmsFondsManages = upmsFondsManageService.selectByExample(example);
        return upmsFondsManages;
    }

    @ApiOperation(value = "新增全宗")
    @RequiresPermissions("upms:fonds:create")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String create() {
        return "/manage/fonds/create";
    }

    @ApiOperation(value = "新增全宗")
    @RequiresPermissions("upms:fonds:create")
    @ResponseBody
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public Object create(UpmsFondsManage upmsFondsManage){
        ComplexResult result = FluentValidator.checkAll()
                .on(upmsFondsManage.getFondsNum(), new LengthValidator(1, 20, "全宗号"))
                .on(upmsFondsManage.getFondsName(), new LengthValidator(1, 50, "组织机构名"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors());
        }

        try {
            Date cTime = DateTimeUtil.getNowDate();
            upmsFondsManage.setCtime(cTime);
        }catch (Exception e){

        }
        upmsFondsManage.setStr1("0");
        //添加全宗前，判断全宗号是否存在
        UpmsFondsManageExample fondsManageExample = new UpmsFondsManageExample();
        fondsManageExample.createCriteria().andStr1EqualTo("0").andFondsNumEqualTo(upmsFondsManage.getFondsNum());
        List<UpmsFondsManage> upmsFondsManages = upmsFondsManageService.selectByExample(fondsManageExample);
        //如果存在，则直接返回，表示此全宗号已有，反之，添加
        if (!upmsFondsManages.isEmpty()){
            return new UpmsResult(UpmsResultConstant.FAILED, "此全宗号已存在，请重命名");
        }
        //添加全宗前，判断组织机构是否已经存在
        fondsManageExample.clear();
        fondsManageExample.createCriteria().andStr1EqualTo("0").andFondsNameEqualTo(upmsFondsManage.getFondsName());
        List<UpmsFondsManage> upmsFondsManages1 = upmsFondsManageService.selectByExample(fondsManageExample);
        if (!upmsFondsManages1.isEmpty()){
            return new UpmsResult(UpmsResultConstant.FAILED, "此组织机构已有全宗，请勿重复添加");
        }
        //添加全宗成功
        int fondsId = upmsFondsManageService.insertSelectFondsId(upmsFondsManage);
        //将当前全宗id关联到内置实体分类
        UpmsArchivesTypesExample typesExample = new UpmsArchivesTypesExample();
        typesExample.createCriteria().andFondsIdEqualTo(0);
        typesExample.setOrderByClause("SORT_NUM ASC");
        List<UpmsArchivesTypes> upmsArchivesTypes =
                upmsArchivesTypesService.selectByExample(typesExample);
        List<UpmsArchivesTypes> types = new ArrayList<>();
        for (UpmsArchivesTypes type:upmsArchivesTypes){
            type.setArchivesId(null);
            type.setFondsId(fondsId);
            types.add(type);
        }
        for (UpmsArchivesTypes type:types){
            try {
                Date cTime = DateTimeUtil.getNowDate();
                type.setCtime(cTime);
                upmsArchivesTypesService.insert(type);
            }catch (Exception e){

            }
        }
        return new UpmsResult(UpmsResultConstant.SUCCESS, fondsId);
    }

    @ApiOperation(value = "修改全宗")
    @RequiresPermissions("upms:fonds:update")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
    public String update(@PathVariable("id") int id, ModelMap modelMap) {
        UpmsFondsManage upmsFondsManage = upmsFondsManageService.selectByPrimaryKey(id);
        modelMap.put("upmsFondsManage",upmsFondsManage);
        return "/manage/fonds/update";
    }
    @ApiOperation(value = "修改全宗")
    @RequiresPermissions("upms:fonds:update")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Object update(@PathVariable("id") int id, UpmsFondsManage upmsFondsManage) {
        ComplexResult result = FluentValidator.checkAll()
                .on(upmsFondsManage.getFondsNum(), new LengthValidator(1, 20, "全宗号"))
                .on(upmsFondsManage.getFondsName(), new LengthValidator(1, 50, "组织机构名"))
                .doValidate()
                .result(ResultCollectors.toComplex());
        if (!result.isSuccess()) {
            return new UpmsResult(UpmsResultConstant.INVALID_LENGTH, result.getErrors());
        }
        UpmsFondsManageExample example = new UpmsFondsManageExample();
        example.createCriteria().andStr1EqualTo("0").andFondsNumEqualTo(upmsFondsManage.getFondsNum());
        List<UpmsFondsManage> upmsFondsManages = upmsFondsManageService.selectByExample(example);
        if (!upmsFondsManages.isEmpty()){
            if (id != upmsFondsManages.get(0).getFondsId()){
                return new UpmsResult(UpmsResultConstant.FAILED, "此全宗已经存在，请重新编辑");
            }
        }
        example.clear();
        example.createCriteria().andStr1EqualTo("0").andFondsNameEqualTo(upmsFondsManage.getFondsName());
        List<UpmsFondsManage> upmsFondsManages1 = upmsFondsManageService.selectByExample(example);
        if (!upmsFondsManages1.isEmpty()){
            if (id != upmsFondsManages1.get(0).getFondsId()){
                return new UpmsResult(UpmsResultConstant.FAILED, "此组织机构已有全宗，请重新编辑");
            }
        }
        upmsFondsManage.setFondsId(id);
        try {
            Date mTime = DateTimeUtil.getNowDate();
            upmsFondsManage.setMtime(mTime);
        }catch (Exception e){

        }
        int count = upmsFondsManageService.updateByPrimaryKeySelective(upmsFondsManage);
        return new UpmsResult(UpmsResultConstant.SUCCESS, count);
    }


    @ApiOperation(value = "删除全宗")
    @RequiresPermissions("upms:fonds:delete")
    @RequestMapping(value = "/delete/{ids}",method = RequestMethod.GET)
    @ResponseBody
    public Object delete(@PathVariable("ids") String ids) {
        //删除全宗，将当前选中的全宗的状态改为1（1代表删除）
        String[] idArray = ids.split("-");
        int count = 0;
        for (String idStr : idArray) {
            if (StringUtils.isBlank(idStr)) {
                continue;
            }
            Integer id = Integer.parseInt(idStr);
            UpmsFondsManage upmsFondsManage = upmsFondsManageService.selectByPrimaryKey(id);
            if ("1".equals(upmsFondsManage.getStr2())){
                return new UpmsResult(UpmsResultConstant.FAILED, "全宗"+upmsFondsManage.getFondsNum()+"已被引用，不可删除");
            }else{
                upmsFondsManage.setStr1("1");
                int i = upmsFondsManageService.updateByPrimaryKey(upmsFondsManage);
                count += i;
            }

        }
        return new UpmsResult(UpmsResultConstant.SUCCESS, count);
    }
}